import 'dart:math';
import 'package:flutter/services.dart';

import 'package:image/image.dart' as img;

import '../graffiti/GraffitiSourceBean.dart';
import 'GifSourceBean.dart';




class GifDecodeUtil {
  late img.GifDecoder decoder;
  final String name;
  final int id;
  late GifSourceBean gifBean;

  GifDecodeUtil(this.name, this.id, Size size, Uint8List bytes) {
    decoder = img.GifDecoder(bytes);
    gifBean = GifSourceBean();
    gifBean.screenSize = size;
  }

  GifSourceBean? caretGifBean() {
    gifBean.id = id;
    gifBean.name = name;
    var info = decoder.info;
    if (info == null) {
      return null;
    }
    gifBean.screenSize = Size(info.width.toDouble(), info.height.toDouble());

    ///赋值帧数
    int d = duration;

    print("总动画时长：$d");
/*    if (d == 0) {
      gifBean.speed = 15;
    } else {
      int tmpSpeed = (1000 / (d / info.numFrames)).toInt();
      tmpSpeed = min(15, tmpSpeed);
      tmpSpeed = max(1, tmpSpeed);
      gifBean.speed = tmpSpeed;
    }*/
    var tmpD = d / info.frames.length / 20;
    print("播放速度：${tmpD}");
    tmpD = max(1, tmpD);
    tmpD = min(40, tmpD);
    print("播放速度：${tmpD}");
    gifBean.speed = tmpD.toInt();

    img.Image drawImage = img.Image(width: info.width, height: info.height);

    Color getColor(int x, int y) {
      var color = drawImage.getPixel(x, y);
      return Color.fromRGBO(color.r.toInt(), color.g.toInt(), color.b.toInt(), 255);
    }

    void setColor(int x, int y, Color c){
      drawImage.setPixel(x, y, img.ColorRgba8(c.red, c.green, c.blue, c.alpha));
    }


    for (var i = 0; i < decoder.numFrames(); i++) {
      img.Image? decodeFrame = decoder.decodeFrame(i);
      if (decodeFrame == null) {
        continue;
      }

      //print("停留时间：${graffitiBean.speed}");
      int offsetX = info.frames[i].x;
      int offsetY = info.frames[i].y;

      for (var y = 0; y < decodeFrame.height; y++) {
        for (var x = 0; x < decodeFrame.width; x++) {
          Color color;
          var a = decodeFrame.getPixel(x, y).a;
          var r = decodeFrame.getPixel(x, y).r;
          var g = decodeFrame.getPixel(x, y).g;
          var b = decodeFrame.getPixel(x, y).b;
          color = Color.fromARGB(a.toInt(), r.toInt(), g.toInt(), b.toInt());

          var col = getColor(x + offsetX, y + offsetY);

          color = mixColors(col, color);
          setColor(x + offsetX, y + offsetY,  color);
        }
      }

      var b = GraffitiSourceBean.formImage(drawImage);
      b.speed = gifBean.speed;
      gifBean.addFrame(b);
    }

    return gifBean;
  }

  ///获取总时长
  get duration {
    double time = 0;
    var info = decoder.info;
    if (info != null) {
      for (var i = 0; i < decoder.numFrames(); i++) {
        time += max(5,info.frames[i].duration)*10;
        print("动画时长：${info.frames[i].duration}");
      }
    }
    return time.toInt();
  }

  Color mixColors(Color colorA, Color colorB) {
    return Color.alphaBlend(colorB, colorA);
  }
}
